import { isArray, isObject, isString, ShapeFlags } from "@vue/shared";

function normalizeChildren(vnode, children) {
  let type = 0;
  if (children == null) { // 不存在子元素

  } else if (isArray(children)) {
    type = ShapeFlags.ARRAY_CHILDREN;
  } else {
    type = ShapeFlags.TEXT_CHILDREN;
  }
  // vnode.shapeFlag |= type; 
  // 或者
  vnode.shapeFlag = vnode.shapeFlag | type;
}

/**
 * 创建虚拟节点
 * @param type 用来区分是组件还是元素
 * @param props 组件或者元素的属性
 * @param children 对于组件来说事插槽，对于元素来说就是元素
 */
export function createVNode(type, props, children = null) {
  // type 区分是组件还是元素
  const shapeFlag = isString(type) ?
    ShapeFlags.ELEMENT : isObject(type) ?
      ShapeFlags.STATEFUL_COMPONENT : 0;

  // vnode 描述 DOM 
  const vnode = {
    __v_isVnode: true,
    type,
    props,
    children,
    component: null, // 存放组件对应的实例
    el: null, // 将真实 DOM 和虚拟 DOM 对应
    key: props && props.key, // 用作 diff
    shapeFlag  // 判断出当前自己的类型和子元素的类型
  };

  normalizeChildren(vnode, children);
  return vnode;
}

export function isVnode (vnode) {
  return vnode.__v_isVnode;
}

export const Text = Symbol('Text');
export function normalizeVNode(child) {
  if (isObject(child)) return child;

  return createVNode(Text, null, String(child));
}